<template>
  <div class="page-container main-view">
    <el-row
      :gutter="0"
      v-show="dataContainer.showSearch"
      class="page-query-box"
    >
      <el-col :span="24" :xs="24">
        <el-form
          :model="dataContainer.form"
          ref="QueryFormRef"
          :inline="true"
          label-width="110px"
        >
          <el-row :gutter="0">
            <el-col :span="6" :xs="6">
              <el-form-item label="操作类型名称" prop="name">
                <el-input
                  v-model="dataContainer.form.name"
                  placeholder="请输入操作类型名称"
                  clearable
                  @clear="handleQuery"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label="状态" prop="isActive">
                <el-select
                  v-model="dataContainer.form.isActive"
                  placeholder="请选择状态"
                  clearable
                  @clear="handleQuery"
                >
                  <el-option label="启用" :value="true" />
                  <el-option label="停用" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="6">
              <el-form-item label=" ">
                <el-button type="primary" @click="handleQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:search-bt.svg"
                  ></SvgIcon>
                  查询
                </el-button>
                <el-button @click="resetQuery">
                  <SvgIcon
                    :style="'width:15px;height:15px;margin-right:5px;'"
                    name="svg:redo.svg"
                  ></SvgIcon>
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <div class="table-box content-container page-content-box">
      <div class="top-container">
        <div class="left">
          <el-button
            v-if="hasPermi(['sys:operation-type:add'])"
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            plain
            type="primary"
            v-if="hasPermi(['sys:operation-type:export'])"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button
            plain
            type="danger"
            v-if="
              dataContainer.currDataList.length > 0 &&
              hasPermi(['sys:operation-type:delete'])
            "
            @click="handleDelete(dataContainer.currDataList)"
          >
            批量删除
          </el-button>
        </div>
        <div class="right">
          <el-button circle @click="resetQuery">
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:redo.svg"
            ></SvgIcon>
          </el-button>
          <el-button
            circle
            @click="dataContainer.showSearch = !dataContainer.showSearch"
          >
            <SvgIcon
              :style="'width:15px;height:15px;'"
              name="svg:search-bt.svg"
            ></SvgIcon>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="dataContainer.loading"
          :data="dataContainer.list"
          border
          @selection-change="handleSelectionChange"
          @cell-dblclick="handleCopyVale"
          @sort-change="handleSortChange"
          height="100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
            fixed="left"
          />
          <el-table-column
            label="ID"
            show-overflow-tooltip
            align="center"
            min-width="120"
            prop="id"
          />
          <el-table-column
            label="操作类型名称"
            show-overflow-tooltip
            align="center"
            min-width="150"
            prop="name"
          />
          <el-table-column
            label="描述"
            show-overflow-tooltip
            align="center"
            min-width="200"
            prop="description"
          />
          <el-table-column
            label="状态"
            show-overflow-tooltip
            align="center"
            min-width="100"
            prop="isActive"
          >
            <template #default="scope">
              <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
                {{ scope.row.isActive ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            show-overflow-tooltip
            align="center"
            min-width="170"
            prop="createdAt"
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="280"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button :text="true" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                :text="true"
                v-if="scope.row.isActive"
                type="warning"
                @click="handleDeactivate(scope.row)"
                v-hasPermi="['sys:operation-type:deactivate']"
              >
                停用
              </el-button>
              <el-button
                :text="true"
                v-else
                type="success"
                @click="handleActivate(scope.row)"
                v-hasPermi="['sys:operation-type:activate']"
              >
                启用
              </el-button>
              <el-button
                :text="true"
                type="danger"
                @click="handleDelete([scope.row.id])"
                v-hasPermi="['sys:operation-type:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          v-show="true"
          :total="dataContainer.config.total"
          :background="true"
          :current-page="dataContainer.params.page"
          :page-size="dataContainer.params.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          :pager-count="7"
          @size-change="
            (size) => {
              dataContainer.params.limit = size;
              getDataList();
            }
          "
          @current-change="
            (page) => {
              dataContainer.params.page = page;
              getDataList();
            }
          "
        />
      </div>
    </div>
    <EditOperationTypeDialog ref="EditOperationTypeDialogRef"></EditOperationTypeDialog>
  </div>
</template>

<script>
/**
 * 操作类型管理页面
 */
import {
  defineComponent,
  onBeforeUnmount,
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onMounted,
  nextTick,
} from "vue";
import { useRouter } from "vue-router";
import { copyValue } from "@/common/OtherTools";
import { debounceFn } from "@/common/DebounceAndThrottle";
import {
  messageSuccess,
  messageError,
  confirm,
} from "@/action/MessagePrompt.js";
import SvgIcon from "@/components/svgIcon/index.vue";
import { hasPermi } from "@/action/PowerTools";
import operationTypesApi from "@/http/operationTypes.js";
import EditOperationTypeDialog from "./components/EditOperationTypeDialog.vue";

export default defineComponent({
  components: {
    SvgIcon,
    EditOperationTypeDialog,
  },
  setup() {
    onMounted(() => {
      getDataList();
    });

    const EditOperationTypeDialogRef = ref(null); //组件实例
    const router = useRouter();
    const dataContainer = reactive({
      loading: false,
      showSearch: true,
      form: {
        name: "",
        isActive: null
      },
      params: {
        page: 1,
        limit: 10,
      },
      config: {
        total: 0,
      },
      list: [],
      allData: [],
      currDataList: [], // 初始化选择的数据列表
    });

    /** 格式化日期时间 */
    function formatDateTime(dateTime) {
      if (!dateTime) return "-";
      const date = new Date(dateTime);
      return date.toLocaleString();
    }

    /** 获取数据列表 */
    const getDataList = debounceFn(function () {
      dataContainer.loading = true;

      // 构建查询参数
      const params = {
        page: dataContainer.params.page,
        limit: dataContainer.params.limit,
        name: dataContainer.form.name || undefined,
        isActive: dataContainer.form.isActive
      };

      operationTypesApi
        .getOperationTypes(params)
        .then((res) => {
          dataContainer.allData = res || [];
          dataContainer.config.total = dataContainer.allData.length;
          updatePageData();
        })
        .catch((err) => {
          console.error("获取操作类型列表失败", err);
          dataContainer.allData = [];
          dataContainer.list = [];
          dataContainer.config.total = 0;
        })
        .finally(() => {
          dataContainer.loading = false;
        });
    }, 300);

    function updatePageData() {
      const start = (dataContainer.params.page - 1) * dataContainer.params.limit;
      const end = start + dataContainer.params.limit;
      dataContainer.list = dataContainer.allData.slice(start, end);
    }

    /** 表格选择项变更 */
    function handleSelectionChange(selection) {
      dataContainer.currDataList = selection;
    }

    /** 双击单元格，复制单元格内容 */
    function handleCopyVale(_, __, ___, event) {
      copyValue(event.target.innerText);
      messageSuccess("复制成功，内容为：" + event.target.innerText);
    }

    /** 排序触发事件 */
    function handleSortChange(column) {
      dataContainer.form.orderByColumn = column.prop;
      dataContainer.form.isAsc = column.order;
      getDataList();
    }

    /** 搜索按钮操作 */
    function handleQuery() {
      dataContainer.params.page = 1;
      getDataList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
      dataContainer.form = {
        name: "",
        isActive: null
      };
      handleQuery();
    }

    /** 导出数据 */
    function handleExport() {
      // 导出功能实现
      console.log("导出操作类型数据");
    }

    /** 新增按钮操作 */
    function handleAdd() {
      nextTick(() => {
        EditOperationTypeDialogRef.value
          .initData(true, {}, { isAdd: true, afterTitle: "-新增" })
          .then(() => {
            getDataList();
          })
          .catch(() => {});
      });
    }

    /** 编辑按钮操作 */
    function handleEdit(row) {
      operationTypesApi.getOperationTypeDetail(row.id).then((res) => {
        nextTick(() => {
          EditOperationTypeDialogRef.value
            .initData(true, res, { isAdd: false, afterTitle: "-编辑" })
            .then(() => {
              getDataList();
            })
            .catch(() => {});
        });
      });
    }

    /** 停用操作类型 */
    function handleDeactivate(row) {
      confirm("确认停用该操作类型?")
        .then(() => {
          dataContainer.loading = true;
          operationTypesApi.deactivateOperationType(row.id)
            .then(() => {
              messageSuccess("停用成功");
              getDataList();
            })
            .catch((err) => {
              messageError("停用失败");
              console.error("停用操作类型失败", err);
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {});
    }

    /** 启用操作类型 */
    function handleActivate(row) {
      confirm("确认启用该操作类型?")
        .then(() => {
          dataContainer.loading = true;
          operationTypesApi.activateOperationType(row.id)
            .then(() => {
              messageSuccess("启用成功");
              getDataList();
            })
            .catch((err) => {
              messageError("启用失败");
              console.error("启用操作类型失败", err);
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {});
    }

    /** 删除操作类型 */
    function handleDelete(idsOrRows) {
      // 处理传入参数：可能是ID数组或行对象数组
      const ids = Array.isArray(idsOrRows) && idsOrRows.length > 0 
        ? (typeof idsOrRows[0] === 'object' ? idsOrRows.map(row => row.id) : idsOrRows)
        : [];
      
      if (ids.length === 0) {
        messageError("请选择要删除的操作类型");
        return;
      }

      const message = ids.length > 1 ? `确认删除选中的 ${ids.length} 个操作类型？` : "确认删除该操作类型？";
      confirm(message)
        .then(() => {
          dataContainer.loading = true;
          // 批量删除操作类型，使用 Promise.allSettled 来处理部分成功的情况
          const deletePromises = ids.map(id => operationTypesApi.deleteOperationType(id));
          Promise.allSettled(deletePromises)
            .then((results) => {
              const successfulDeletes = results.filter(result => result.status === 'fulfilled').length;
              const failedDeletes = results.filter(result => result.status === 'rejected').length;
              
              if (successfulDeletes > 0) {
                messageSuccess(`成功删除 ${successfulDeletes} 个操作类型`);
              }
              
              if (failedDeletes > 0) {
                messageError(`${failedDeletes} 个操作类型删除失败`);
              }
              
              getDataList();
            })
            .catch((err) => {
              console.error("删除操作类型处理异常", err);
              messageError("删除操作类型处理异常");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        })
        .catch(() => {});
    }

    return {
      dataContainer,
      getDataList,
      handleSelectionChange,
      handleCopyVale,
      handleSortChange,
      handleQuery,
      resetQuery,
      handleAdd,
      handleEdit,
      handleDeactivate,
      handleActivate,
      handleDelete,
      handleExport,
      EditOperationTypeDialogRef,
      hasPermi,
      formatDateTime,
    };
  },
});
</script>

<style lang="scss" scoped>
.main-view {
  display: flex;
  flex-direction: column;
  > .page-query-box {
    margin: 0 0 10px 0 !important;
    padding: 10px 10px 0px 10px;
    :deep(.el-form-item) {
      margin-bottom: 10px !important;
    }
    :deep(.el-form-item--default) {
      width: 100%;
      margin-right: 0;
    }
  }
  > .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px 10px;
    box-sizing: border-box;
    background: #fff;
    > .top-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0px 0 10px 0;
    }
    > .table-container {
      flex: 1 1 auto;
      height: 0;
      overflow: auto;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 0;
    margin: 10px 0 0 0;
  }
}
</style>
